import { Injectable } from '@nestjs/common';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';

import { JwtService } from '@nestjs/jwt';
import { UserEntity } from '../user/entities/user.entity';

import { ToolUtil } from 'src/utils/tool.util';

@Injectable()
export class AuthService {
  constructor(
    @InjectRepository(UserEntity)
    private readonly userRepository: Repository<UserEntity>,
    private readonly jwtService: JwtService,
    private readonly toolUtil: ToolUtil,
  ) {}

  /* 登录 */
  async login(user): Promise<any> {
    const payload = { id: user.id, username: user.username };
    return {
      token: this.jwtService.sign(payload),
    };
  }

  /* 校验登录 */
  async validateUser(id: string, password: string): Promise<any> {
    // 校验用户
    const user = await this.userRepository.findOne({
      relations: { role: true },
      where: { id },
      select: ['id', 'username', 'phone', 'email', 'salt', 'password'],
    });
    if (
      user &&
      user.password === this.toolUtil.addSalt(password, user.salt).text
    ) {
      const { ...result } = user;
      return result;
    }
    return false;
  }
}
